﻿using System;
using System.Web;
using Coleotrack.Service.Contracts;
using StructureMap;

namespace Coleotrack.Web
{
    public class NHibernateModule : IHttpModule
    {
        private INHibernateUnitOfWork unitOfWork;

        public void Init(HttpApplication context)
        {
            context.BeginRequest += ContextBeginRequest;
            context.EndRequest += ContextEndRequest;
        }

        private void ContextBeginRequest(object sender, EventArgs e)
        {
            unitOfWork = ObjectFactory.TryGetInstance<INHibernateUnitOfWork>();
        }

        private void ContextEndRequest(object sender, EventArgs e)
        {
            if (unitOfWork == null) return;

            try
            {
                unitOfWork.Commit();
            }
            catch (Exception ex)
            {
                unitOfWork.Rollback();
                throw;
            }
        }

        public void Dispose()
        {
            //unitOfWork.Dispose();
        }
    }
}